package com.yycx.module.bus.provider.handler.haiying.report;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.module.export.DictDataVo;
import com.yycx.common.base.module.export.ExportField;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.interceptor.ExportInterceptor;
import com.yycx.common.mybatis.interceptor.PageInterceptor;
import com.yycx.common.mybatis.model.PageParams;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.DateUtils;
import com.yycx.common.utils.RedisUtils;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.client.entity.hy.HyOrderDetail;
import com.yycx.module.bus.client.enums.HySaleTypeEnum;
import com.yycx.module.bus.client.enums.SaleTypeEnum;
import com.yycx.module.bus.provider.service.BusInvoiceunitService;
import com.yycx.module.bus.provider.service.BusOrderDetailsService;
import com.yycx.module.bus.provider.service.BusOrderService;
import com.yycx.module.bus.provider.service.BusPaymentService;
import com.yycx.module.system.provider.service.SysBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 非两票业务明细表
 *
 * @author zyf
 */
@Component
public class HyOrderDetailsReportHandler implements PageInterceptor<HyOrderDetail>, ExportInterceptor<HyOrderDetail> {


    @Autowired
    private BusPaymentService paymentService;


    @Autowired
    private BusOrderService orderService;

    @Autowired
    private BusInvoiceunitService invoiceunitService;

    @Autowired
    private SysBankService bankService;

    @Autowired
    private RedisUtils redisUtils;


    @Override
    public void prepare(CriteriaQuery<HyOrderDetail> cq, PageParams pageParams, EntityMap params) {
        String orderNo = params.get("orderNo");
        Long companyId = params.getLong("companyId");
        String saleType = params.get("saleType");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        cq.likeLeft(FlymeUtils.isNotEmpty(params.get("orderNo")), "outOrderNo", orderNo);
        cq.eq(HyOrder.class, "deptId");
        cq.eq(HyOrder.class, "sendType");
        //排除未提交
        cq.ne("ho.orderState", CommonConstants.INT_0);
        cq.like(BusCustom.class, "customName");
        cq.like(HyOrderDetail.class, "drugsName");
        if (FlymeUtils.isNotEmpty(beginDate)) {
            cq.ge(HyOrderDetail.class, "sendDate", beginDate);
        }
        if (FlymeUtils.isNotEmpty(endDate)) {
            cq.le(HyOrderDetail.class, "sendDate", endDate);
        }
        if (FlymeUtils.isNotEmpty(saleType)) {
            cq.in(true, "saleType", saleType.split(","));
        }
        cq.eq(true, "bhd.companyId", companyId);
        cq.addSelect(HyOrder.class, "orderNo", "outOrderNo", "remark", "sendDate","orderType", "sendType", "customBondType", "saleManName", "businessCode", "businessArea", "takeDate");
        cq.addSelect(BusDept.class, "deptName");
        cq.addSelect(BusCustom.class, "customName");
        cq.createJoin(BusDept.class);
        cq.createJoin(BusCustom.class);
        cq.orderByDesc("ho.sendDate");
    }

    @Override
    public List<EntityMap> complete(CriteriaQuery<HyOrderDetail> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap entityMap : result) {
            //getCustomReturnState(entityMap);
            //getCustomBond(entityMap);
            //getSupplierRefundState(entityMap);
            //getSettleState(entityMap);
        }
        //是否是财务角色
        Boolean isCw = false;
        //是否允许核算
        Boolean calculate = OpenHelper.hasRole("ROLE_CW_JSY", "ROLE_CW_FHY", "ROLE_CW_JSBX", "ROLE_CW_ZJ");
        if (calculate) {
            isCw = true;
        }
        extra.put("calculate", calculate);
        extra.put("isCw", isCw);
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isNotEmpty(userId)) {
            cq.setExportKey("flp:report:" + userId);
        }
        return result;

    }


    /**
     * 查询资保金收款
     */
    private Boolean getCustomBond(EntityMap entityMap) {
        //销售类型
        String saleType = entityMap.get("saleType");
        Long orderId = entityMap.getLong("orderId");
        BigDecimal customBond = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("customBond"), "0");
        BigDecimal overAmount = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("customOverBond"), "0");
        Integer cbState = entityMap.getInt("customBondState");
        String customBondState = "";
        String takeDate = "";
        BigDecimal customBondTake = new BigDecimal("0");
        BusOrder order = orderService.getById(orderId);
        if (FlymeUtils.isNotEmpty(order)) {
            takeDate = DateUtils.formatDate(order.getTakeDate(), "yyyy-MM-dd");
        }
        //资保金方式
        Integer customBondType = entityMap.getInt("customBondType");
        if (customBondType > 0 && !customBondType.equals(7) && !customBondType.equals(5) && saleType.equals(HySaleTypeEnum.CHA.getCode())) {
            //保证金状态
            customBondTake = overAmount.add(customBond);
            if (cbState.equals(1)) {
                customBondState = "已认款";
            }
            if (cbState.equals(0)) {
                customBondState = "未认款";
            }
        } else {
            if (customBondType.equals(0)) {
                if (FlymeUtils.isNotEmpty(order)) {
                    //全款回款日期
                    //entityMap.put("returnDate", takeDate);
                }
            }
            takeDate = "-";
            customBondTake = overAmount.add(customBond);
            customBondState = "-";
        }
        BigDecimal returnCustomBond = entityMap.getBigDecimal("returnCustomBond");
        String customBondRetDate = entityMap.get("customBondRetDate");
        if (cbState.equals(2)) {
            customBondState = "已退款";
        }
        entityMap.put("returnCustomBondDate", customBondRetDate);
        entityMap.put("takeDate", takeDate);
        entityMap.put("customBond", customBond);
        entityMap.put("overAmount", overAmount);
        entityMap.put("customBondTake", customBondTake);
        entityMap.put("customBondState", customBondState);
        return true;
    }


    /**
     * 查询市场回款状态
     */
    private Boolean getCustomReturnState(EntityMap entityMap) {
        Long orderDetailsId = entityMap.getLong("orderDetailsId");
        EntityMap resultMap = new EntityMap();
        //订单类型
        Integer saleType = entityMap.getInt("saleType");
        //回款金额
        BigDecimal returnAmount = entityMap.getBigDecimal("returnAmount");
        String returnDate = FlymeUtils.getString(entityMap.get("returnDate"));
        //回款状态
        String customReturnState = "未回款";
        if (HySaleTypeEnum.CHA.getCode().equals(saleType)) {
            if (FlymeUtils.gtzero(returnAmount)) {
                customReturnState = "已回款";
            }
        }
        if (!saleType.equals(1)) {
            if (FlymeUtils.nezero(returnAmount)) {
                if (saleType.equals(HySaleTypeEnum.CHC.getCode())) {
                    customReturnState = "已退款";
                }
                if (saleType.equals(HySaleTypeEnum.Bh.getCode())) {
                    customReturnState = "已回款";
                }
            }
        }
        resultMap.put("customReturnState", customReturnState);
        resultMap.put("returnAmount", returnAmount);
        resultMap.put("returnDate", returnDate);
        entityMap.putAll(resultMap);
        return true;
    }

    /**
     * 查询厂家返款和开票状态
     */
    private Boolean getSupplierRefundState(EntityMap entityMap) {
        Long kaipiaoId = entityMap.getLong("kaipiaoId");
        //返款状态
        Integer supplierRefundState = entityMap.getInt("supplierRefundState");
        EntityMap resultMap = new EntityMap();
        String supplierRefundStateText = "未返款";
        String supplierRefundAmountDate = "";
        Integer saleType = entityMap.getInt("saleType");
        BigDecimal invoicePaymentAmount = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("invoicePaymentAmount"), "0");
        BigDecimal invoiceSj = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("invoiceSj"), "0");
        String invoiceAmountDate = FlymeUtils.getString(entityMap.get("invoiceAmountDate"), "");
        String invoicePaymentNo = FlymeUtils.getString(entityMap.get("invoicePaymentNo"), "");
        String invoiceunitName = FlymeUtils.getString(entityMap.get("invoiceunitName"), "");
        if (supplierRefundState.equals(1)) {
            supplierRefundStateText = "已开票";
        }
        BigDecimal supplierRefundAmount = entityMap.getBigDecimal("supplierRealAmount");
        //计算返款
        if (FlymeUtils.isNotEmpty(supplierRefundAmount) && FlymeUtils.nezero(supplierRefundAmount)) {
            supplierRefundStateText = "已返款";
            supplierRefundAmountDate = entityMap.get("supplierRetDate");
        }
        resultMap.put("invoiceunitName", invoiceunitName);
        resultMap.put("invoicePaymentAmount", invoicePaymentAmount);
        resultMap.put("invoiceSj", invoiceSj);
        resultMap.put("invoiceAmountDate", invoiceAmountDate);
        resultMap.put("invoicePaymentNo", invoicePaymentNo);
        resultMap.put("supplierRefundState", supplierRefundStateText);
        resultMap.put("supplierRefundAmount", supplierRefundAmount);
        resultMap.put("supplierRefundAmountDate", supplierRefundAmountDate);

        entityMap.putAll(resultMap);
        return true;
    }

    /**
     * 查询结算状态
     */
    private Boolean getSettleState(EntityMap entityMap) {
        EntityMap resultMap = new EntityMap();
        String settleState = "未结算";
        Long orderDetailsId = entityMap.getLong("orderDetailsId");
        //销售类型
        Integer saleType = entityMap.getInt("saleType");
        BigDecimal settleAmount = entityMap.getBigDecimal("settleAmount");
        BigDecimal settleRealAmount = entityMap.getBigDecimal("settleRealAmount");
        BigDecimal settleAmount2 = entityMap.getBigDecimal("settleAmount2");
        BigDecimal settleAmount3 = entityMap.getBigDecimal("settleAmount3");
        BigDecimal settleRealAmount2 = entityMap.getBigDecimal("settleRealAmount2");
        BigDecimal settleRealAmount3 = entityMap.getBigDecimal("settleRealAmount3");
        Integer state = entityMap.getInt("settleState");
        Integer state2 = entityMap.getInt("settleState2");
        Integer state3 = entityMap.getInt("settleState3");
        Integer state4 = state + state2 + state3;
        //未结算金额=0
        if (state.equals(2)) {
            settleState = "已结算";
        }
        entityMap.put("settleAmount", settleAmount);
        entityMap.put("settleRealAmount", settleRealAmount);
        entityMap.put("settleAmount2", settleAmount2);
        entityMap.put("settleRealAmount2", settleRealAmount2);
        entityMap.put("settleRealAmount3", settleRealAmount3);
        entityMap.put("settleState", settleState);
        return true;

    }


    @Override
    public void initExcelExportEntity(ExportField exportField, List list) {
        Object key = exportField.getKey();
        if (key.equals("orderNo")) {
            exportField.setWidth(15);
        }
        if (key.equals("invoiceAmount")) {
            exportField.setMergeVertical(true);
        }
        if (key.equals("deptType")) {
            List<DictDataVo> dictDataVos = new ArrayList<>();
            DictDataVo dictDataVo = new DictDataVo();
            dictDataVo.setLabel("自营");
            dictDataVo.setValue("ZY");
            DictDataVo dictDataVo2 = new DictDataVo();
            dictDataVo2.setLabel("招商");
            dictDataVo2.setValue("ZS");
            dictDataVos.add(dictDataVo);
            dictDataVos.add(dictDataVo2);
            exportField.setDictData(dictDataVos);
            exportField.setReplace();
        }
        if (key.equals("sendType")) {
            List<DictDataVo> dictDataVos = new ArrayList<>();
            DictDataVo dictDataVo = new DictDataVo();
            dictDataVo.setLabel("现款");
            dictDataVo.setValue(1);
            DictDataVo dictDataVo2 = new DictDataVo();
            dictDataVo2.setLabel("预付款");
            dictDataVo2.setValue(2);
            DictDataVo dictDataVo3 = new DictDataVo();
            dictDataVo3.setLabel("资保金");
            dictDataVo3.setValue(3);
            DictDataVo dictDataVo4 = new DictDataVo();
            dictDataVo4.setLabel("资信");
            dictDataVo4.setValue(4);
            dictDataVos.add(dictDataVo);
            dictDataVos.add(dictDataVo2);
            dictDataVos.add(dictDataVo3);
            dictDataVos.add(dictDataVo4);
            exportField.setDictData(dictDataVos);
            exportField.setReplace();
        }

        if (key.equals("orderType")) {
            List<DictDataVo> dictDataVos = new ArrayList<>();

            DictDataVo dictDataVo = new DictDataVo();
            dictDataVo.setLabel("销售");
            dictDataVo.setValue("CHA");

            DictDataVo dictDataVo2 = new DictDataVo();
            dictDataVo2.setLabel("报损");
            dictDataVo2.setValue("CKC");

            DictDataVo dictDataVo3 = new DictDataVo();
            dictDataVo3.setLabel("盘损");
            dictDataVo3.setValue("CKD");

            DictDataVo dictDataVo4 = new DictDataVo();
            dictDataVo4.setLabel("赠品");
            dictDataVo4.setValue("CKE");

            DictDataVo dictDataVo5 = new DictDataVo();
            dictDataVo5.setLabel("移出");
            dictDataVo5.setValue("CKF");

            DictDataVo dictDataVo6 = new DictDataVo();
            dictDataVo6.setLabel("其他");
            dictDataVo6.setValue("CKG");


            DictDataVo dictDataVo7 = new DictDataVo();
            dictDataVo7.setLabel("退补");
            dictDataVo7.setValue("CKI");


            DictDataVo dictDataVo8 = new DictDataVo();
            dictDataVo8.setLabel("退货");
            dictDataVo8.setValue("CKJ");


            DictDataVo dictDataVo9 = new DictDataVo();
            dictDataVo9.setLabel("领用");
            dictDataVo9.setValue("CKL");



            dictDataVos.add(dictDataVo);
            dictDataVos.add(dictDataVo2);
            dictDataVos.add(dictDataVo3);
            dictDataVos.add(dictDataVo4);
            dictDataVos.add(dictDataVo5);
            dictDataVos.add(dictDataVo6);
            dictDataVos.add(dictDataVo7);
            dictDataVos.add(dictDataVo8);
            dictDataVos.add(dictDataVo9);
            exportField.setDictData(dictDataVos);
            exportField.setReplace();
        }

    }


    @Override
    public TemplateExportParams initTemplateExportParams(Map params) {
        Long companyId = OpenHelper.getCompanyId();
        TemplateExportParams templateExportParams = new TemplateExportParams("excel/业务明细表.xlsx", true);
        return templateExportParams;
    }

    @Override
    public Map initTemplateDataMap() {
        HashMap<Object, Object> dataMap = new HashMap<>();

        return dataMap;
    }

    @Override
    public void initExportData(Map dataMap,List<EntityMap> list,CriteriaQuery<HyOrderDetail> cq) {
        Long companyId = OpenHelper.getCompanyId();
        if (companyId.equals(5L)) {
            dataMap.put("companyName", "丹博瑞");
        }
        if (companyId.equals(1018L)) {
            dataMap.put("companyName", "赤壁医药(药品)");
        }
        if (companyId.equals(1017L)) {
            dataMap.put("companyName", "赤壁医药(器械)");
        }
        for (EntityMap o : list) {
            String orderType=o.get("orderType");
            if(orderType.equals("CHA")){
                o.put("orderType","销售");
            }
            if(orderType.equals("CKC")){
                o.put("orderType","报损");
            }
            if(orderType.equals("CKD")){
                o.put("orderType","盘损");
            }
            if(orderType.equals("CKE")){
                o.put("orderType","赠品");
            }
            if(orderType.equals("CKF")){
                o.put("orderType","移出");
            }
            if(orderType.equals("CKG")){
                o.put("orderType","其他");
            }
            if(orderType.equals("CKI")){
                o.put("orderType","退补");
            }
            if(orderType.equals("CKJ")){
                o.put("orderType","退货");
            }
            if(orderType.equals("CKL")){
                o.put("orderType","领用");
            }

        }
    }
}
